<?php if (!defined("_ECRIRE_INC_VERSION")) return; if (class_exists('AlohacartClientModel')) return;
/**
 * Aloha Cart
 *
 * @author     Aleksey Yaroshchuk (aleksey.yaroshchuk@gmail.com)
 * @license    GNU/GPL
 * @package    plugins
 * @subpackage alohacart
 * @copyright  (c) Aleksey Yaroshchuk 2011-2012
 * @link       http://www.spip-contrib.net/AlohaCart
 */

//require_once(_DIR_PLUGIN_PDK.'classes/models/PdkAuteurModel.php');

/** 
 *  This is alohacart client model
 *
 *  @author Aleksey Yaroshchuk (aleksey.yaroshchuk@gmail.com)
 */
include_spip('functions/pdk_common');
pdk_load_class('PdkAuteurModel', 'classes/models/');
//include_spip('classes/models/PdkAuteurModel');
class AlohacartClientModel extends PdkAuteurModel {
    /**
     *  PdkAuteurModel
     */
    private $auteur_mdl;
    
    public $registered_statut = 'client_registered';
    public $unregistered_statut = 'client_unregistered';
    
    public function __construct() {
        parent::__construct();
        $this->auteur_mdl = pdk_load_class('PdkAuteurModel','classes/models');
        $this->config_client_model();
        $this->populate_test_data();
    }
    
    function config_client_model() {
        
        // We don't need to config main table, because it is already done in parent class
        // But we can redefine some fields
        $this->main_fields['nom'] = 'name';
        
        // Define join tables:
        $this->joins['spip_alohacart_clients'] = array('main_id'=>'id_auteur',
                                                       'join_id'=>'id_auteur',                                                               
                                                       'join_type'=>'INNER',
                                                       'fields'=>array('id_auteur'=>'id_auteur',
                                                                       'phone'=>'phone',
                                                                       'city'=>'city',
                                                                       'address'=>'address')
                                                       );
                                                       
        $this->joins['spip_alohacart_sources'] = array('main_id'=>'id_auteur',
                                                       'join_id'=>'id_auteur',                                                               
                                                       'join_type'=>'LEFT',
                                                       'fields'=>array('id_auteur'=>'id_auteur',
                                                                       'source'=>'source_source',
                                                                       'medium'=>'source_medium',
                                                                       'term'=>'source_term',
                                                                       'content'=>'source_content',
                                                                       'campaign'=>'source_campaign',
                                                                       'segment'=>'source_segment'
                                                                       )
                                                       );                                               
                                                       
          
         // Define validation rules:         
         $this->validation->set_rules( 
            array(
               array(
                     'field'   => 'name',
                     'label'   => _T('alohacart:name'),
                     'rules'   => 'required'
                  ),
               array(
                     'field'   => 'phone',
                     'label'   => _T('alohacart:phone'),
                     'rules'   => 'required|numeric' // exact_length[10]
                  ),
               array(
                     'field'   => 'email',
                     'label'   => _T('alohacart:email'),
                     'rules'   => 'required|valid_email'
                  )   
            )
         );                             
    }    
     
    private function populate_test_data(){
        $num_test_data = count($this->test_data);
        for ($i=0;$i<$num_test_data;$i++) {
            // nom меняем на name
            $this->test_data[$i]['name'] = 'Client '.$i;
            unset($this->test_data[$i]['nom']);
            // В тестовых данных все клиенты зарегистрированы
            $this->test_data[$i]['statut'] = $this->registered_statut;
            $this->test_data[$i]['phone'] = '123456789';
            $this->test_data[$i]['city'] = 'City '.$i;
            $this->test_data[$i]['address'] = 'Address '.$i;
            $this->test_data[$i]['source_source'] = 'Source '.$i;
            $this->test_data[$i]['source_medium'] = 'Medium '.$i;
            $this->test_data[$i]['source_term'] = 'Term '.$i;
            $this->test_data[$i]['source_content'] = 'Content '.$i;
            $this->test_data[$i]['source_campaign'] = 'Campaign '.$i;
            $this->test_data[$i]['source_segment'] = 'Segment '.$i;
        }
    }
    
    function select($where = array(), $group_by = array(), $order_by = array(), $limit = '') {
        // If statut isn't set, add clients statuts to enshure that we select clients
        //if (!isset($where['statut']))
            //$where['statut'] = "statut='".$this->registered_statut."' OR statut='".$this->unregistered_statut."'";
        $clients = parent::select($where, $group_by, $order_by, $limit = '');
        return $clients;         
    }
    
    function insert($data, $clear_id = false) {
        return parent::insert($data, $clear_id);
    }
    
    function update($where, $data) {
        return parent::update($where, $data); 
    }
    
    /**
     *  Creates and outputs all clients in Excel SpreadSheet format
     */
    public function OutputExcel() {
        require_once _DIR_PLUGIN_EXCEL."pear/Spreadsheet/Excel/Writer.php";
        
        // Creating a workbook
        $workbook = new Spreadsheet_Excel_Writer();    
        $workbook->setTempDir(_DIR_CACHE);
        $workbook->setVersion(8);
        
        // sending HTTP headers
        $workbook->send('clients.xls');
    
        // Let's create catalogue worksheet:
        $this->addWorksheet($workbook);
        
        // Let's send the file
        $workbook->close();
    
        // After file has been sent, just exit:
        exit;
    }
    
    /**
     *  Adds Worksheet with clients to given $workbook
     */
    private function addWorksheet(&$workbook) {
        // Creating worksheet    
        $worksheet =& $workbook->addWorksheet('Clients');
        $worksheet->setInputEncoding('utf-8');
        
        // Format for first line
        $format_bold =& $workbook->addFormat();
        $format_bold->setBold();
        
        $worksheet->write(0, 0, 'ID', $format_bold);
        $worksheet->write(0, 1, _T('alohacart:client_name'), $format_bold);
        $worksheet->write(0, 2, _T('alohacart:client_email'), $format_bold);
        $worksheet->write(0, 3, _T('alohacart:client_phone'), $format_bold);
        $worksheet->write(0, 4, _T('alohacart:client_city'), $format_bold);
        $worksheet->write(0, 5, _T('alohacart:client_address'), $format_bold);
        $worksheet->write(0, 6, _T('alohacart:client_statut'), $format_bold);
        $worksheet->write(0, 7, _T('alohacart:ga_source'), $format_bold);
        $worksheet->write(0, 8, _T('alohacart:ga_medium'), $format_bold);
        $worksheet->write(0, 9, _T('alohacart:ga_term'), $format_bold);
        $worksheet->write(0, 10, _T('alohacart:ga_content'), $format_bold);
        $worksheet->write(0, 11, _T('alohacart:ga_campaign'), $format_bold);
        $worksheet->write(0, 12, _T('alohacart:ga_segment'), $format_bold);
        
        // Set columns width: 
        $worksheet->setColumn(0,12, 15);
        
        $clients = $this->select();        
        foreach ($clients as $key=>$cli) {            
            $worksheet->write($key+1, 0, $cli['id_auteur']);
            $worksheet->write($key+1, 1, $cli['email']);
            $worksheet->write($key+1, 2, $cli['name']);            
            $worksheet->writeString($key+1, 3, $cli['phone']);
            $worksheet->write($key+1, 4, $cli['city']);
            $worksheet->write($key+1, 5, $cli['address']);
            $worksheet->write($key+1, 6, $cli['statut'] == $this->registered_statut ? _T('alohacart:client_statut_registered') : _T('alohacart:client_statut_unregistered'));
            $worksheet->write($key+1, 7, $cli['source_source']);
            $worksheet->write($key+1, 8, $cli['source_medium']);
            $worksheet->write($key+1, 9, $cli['source_term']);
            $worksheet->write($key+1, 10, $cli['source_content']);
            $worksheet->write($key+1, 11, $cli['source_campaign']);
            $worksheet->write($key+1, 12, $cli['source_segment']);
        }        
    }
    
    /**
     *  Register client
     *  @param array $data Data array. It must contain:
     *      $data['register_me'] - if true, client wants to register (i.e. via checkbox) 
     *      $data['email']
     *      $data['name'] - login will be created from name, taking to account that there can't be two auteurs with the same login
     *      ... and other clent's data (i.e. phone, city,...)     
     *  According to given $data and data in DB, there are 4 possible scenarious:
     *  1. Client doesn't want to register and auteur doesn't exist yet - data about client will be put into DB and client will be marked as unregistered
     *  2. Client doesn't want to register but auteur exists already - don't do anything
     *  3. Client wants to register and unregistered client with same email hasn't been created yet - insert data and mark client as registered
     *  4. Client wants to register and unregistered client with same email has been created already - update data and mark client as registered
     * 
     *  NB: On validation level you must ensure that client doesn't try to register on already registered email
     */
    public function RegisterClient($data_request) {
        $data = $this->form_data_from_array($data_request);
    
        if (isset($data_request['register_me']) && $data_request['register_me']) { // Явная регистрация (через галочку)
            $data['statut'] = $this->registered_statut;
            $data['login'] = $this->CreateLoginFromName($data['name']);
            
        while ($this->get_total("login='".$data['login']."'") > 0) {
            $data['login'] .= '_';
        }
        $data['pass'] = $this->CreatePassword();        
        // Если уже есть такой клиент, но раньше он не регистрировался, то апдейтим его        
        if ($this->get_total(array("email='".$data['email']."'", "statut='".$this->unregistered_statut."'")) > 0) {
            $where = array("email='".$data['email']."'", "statut='".$this->unregistered_statut."'");
            $this->update($where, $data);                                    
        } else {               
            $this->insert($data);
        }           
    } else {// Скрытая регистрация (Просто заносим данные пользователя в БД для статистики)
        $data['statut'] = $this->unregistered_statut;
        // Если есть автор - выходим                     
        if ($this->auteur_mdl->get_total("email='".$data['email']."'") > 0)
            return;                         
        
        $this->insert($data);
    }
    }
}
?>